package middleware

import (
	"dealcenter/utils/logx"
	"github.com/gin-gonic/gin"
	"io"
	"os"
	"time"
)

func LogMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 中间件-前
		startTime := time.Now()

		ctx.Next()

		// 中间件-后
		// 业务信息
		endTime := time.Now()
		latencyTime := endTime.Sub(startTime)
		reqMethod := ctx.Request.Method
		reqUri := ctx.Request.RequestURI
		statusCode := ctx.Writer.Status()
		clientIP := ctx.GetHeader("X-Real-IP")
		if clientIP == "" {
			clientIP = ctx.ClientIP()
		}

		// 监控日期变化
		if logx.LogFileCreateTime.Day() != startTime.Day() {
			logx.LogFileLock.Lock()
			_ = logx.LogFile.Close()
			logx.LogFile, _ = logx.NewLogFile()
			logx.LogFileInfo, _ = logx.LogFile.Stat()
			logx.LogFileCreateTime = logx.LogFileInfo.ModTime()
			logx.LogrusObj.SetOutput(io.MultiWriter(logx.LogFile, os.Stdout))
			logx.LogFileLock.Unlock()
		}

		// 终端输出 (colorful)
		//fmt.Print("[API] ", startTime.Format("06/01/02-15:04:05"), " |")
		//fmt.Printf(CCMap[statusCode/100]+" %3d "+CEnd+"| %13v | %15s |"+MCMap[reqMethod]+" %-8s "+CEnd+"| %s \n", statusCode, latencyTime, clientIP, reqMethod, reqUri)

		// writer 输出
		logx.LogrusObj.Infof("[API] | %3d | %13v | %15s | %-8s | %s ",
			statusCode,
			latencyTime,
			clientIP,
			reqMethod,
			reqUri,
		)
	}
}

var (
	CCMap = map[int]string{
		2: "\x1b[42m",
		3: "\x1b[47m",
		4: "\x1b[43m",
		5: "\x1b[41m",
	}
	MCMap = map[string]string{
		"GET":     "\x1b[44m",
		"POST":    "\x1b[46m",
		"PUT":     "\x1b[43m",
		"DELETE":  "\x1b[41m",
		"OPTIONS": "\x1b[47m",
	}
	CEnd = "\x1b[0m"
)
